package com.epfresh.supplier.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.GridViewAdapter;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.Images;
import com.epfresh.api.widget.PhotoUploadView;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.ucrop.PhotoCore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 2016/5/6.
 */
public class UploadStorePictureActivity extends BaseActivity implements PhotoCore.PhotoResult {
    private GridView dgv;
    private GridViewAdapter adapter;
    private List<Images> imgList = new ArrayList<>();
    private int currentIndex = -1;


    private PhotoUploadView currentPhotoUpload;
    private TextView tvBtn;
    private List<PhotoUploadView> list = new ArrayList<>();
    private int currentPhotoUploadIndex = -1;

    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "product_detail";


    private boolean isFirst ;

    private String images = "";

//    private String productId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_store_picture);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText(R.string.pic_detail);
        rightbtn.setText("保存");
        rightbtn.setTextColor(0xff898989);
        rightbtn.setVisibility(View.VISIBLE);
        if (savedInstanceState != null) {
            getIntent().putExtra(Constant.TYPE, savedInstanceState.getInt(Constant.TYPE));
            getIntent().putExtra(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS, savedInstanceState.getString(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS));
        }
        isFirst = getIntent().getBooleanExtra(Constant.TYPE,false);

        filePath += "_" + getUser().getAccountId();
        initView();
        initPhotoCore();
    }

    private void initPhotoCore() {
        photoCore = new PhotoCore(this, this);
        photoCore.setRatio(4,3);
        photoCore.setResultHeight(500);
        photoCore.setResultWidth(500);
    }

    @Override
    public void onRightClick() {
        save();
    }

    private void initView() {
        dgv = (GridView) findViewById(R.id.dgv);
        ViewGroup.LayoutParams layoutParams = dgv.getLayoutParams();
        layoutParams.height = LocalDisplay.SCREEN_WIDTH_PIXELS / 3 * 2;
        adapter = new GridViewAdapter(this, imgList);
        dgv.setAdapter(adapter);

        dgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                currentPhotoUpload = (PhotoUploadView) view;
                Images images = imgList.get(position);

                //添加图片或者上传图片失败
                if (images.isAdd() ) {
                    currentIndex = position;
                    String fp = images.getFilePath();
                    if (fp == null || "".equals(fp)) {
                        images.setFilePath(new File(filePath + "_" + System.currentTimeMillis()).getPath());
                    }
                    photoCore.showPhotoDialog(Uri.fromFile(new File(images.getFilePath())),images.getFilePath(), images.isUploadFail());
                }else if (images.isUploadFail()){
                    images.setType(Images.LOADING);
                    adapter.notifyDataSetChanged();
                    RequestTag tag = new RequestTag();
                    tag.action = currentIndex;
                    tag.tag = "upload";
                    tag.arg1 = images.getUuid();
                    photoCore.uploadImage(UploadStorePictureActivity.this, images.getFilePath(), tag,uploadListener);
                }


            }
        });



        tvBtn = (TextView) findViewById(R.id.tv_btn);
        tvBtn.setOnClickListener(this);


        displayData();
    }

    //加载数据
    private void displayData() {
        images = getIntent().getStringExtra(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS);

        L.e("images", "images:" + images);
        if (!TextUtils.isEmpty(images)) {
            List<Images> imagesList = new Gson().fromJson(images, new TypeToken<List<Images>>() {
            }.getType());
            imgList.clear();

            int bannerCount = 0;
            int detailCount = 0;
            for (int i = 0; i < imagesList.size(); i++) {
                Images images1 = imagesList.get(i);


                boolean cover = images1.isCover();
                boolean banner = images1.isBanner();

                if (banner) {

                } else if (detailCount < 6) {
                    imgList.add(images1);

                    detailCount++;
                }


            }


            adapter.clearAllStatus();
        }


        adapter.addedView();


    }
    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            Log.e("upload","upload_fail");
            if (tag instanceof RequestTag) {
                RequestTag rt = (RequestTag) tag;
                adapter.updateStatus(rt.arg1,null,Images.LOAD_FAIL);
            }

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (tag instanceof RequestTag) {
                RequestTag rt = (RequestTag) tag;
                adapter.updateStatus(rt.arg1,null,Images.LOAD_FAIL);
            }
            Log.e("upload","upload_error");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            Log.e("upload","id="+id);
            if (tag instanceof RequestTag) {
                RequestTag rt = (RequestTag) tag;

                adapter.updateStatus( rt.arg1,id+"",Images.SUCCESS);
            }


        }
    };


    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS,new Gson().toJson(imgList));

        outState.putBoolean(Constant.TYPE, isFirst);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);

        if (view.getId() == R.id.tv_btn) {
            save();
            return;
        }

    }


    private void save() {

        List<Images> images = adapter.getImages();
        if (images.size() < 1) {
            toast("请添加图片");
            return;
        }

        if (adapter.isUploadNotSuccess()){
            toast("请等待图片上传完成");
            return;
        }


        L.d("images","store_images_1:"+images);
        Intent intent = new Intent();
        intent.putExtra(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS, new Gson().toJson(images));

        setResult(RESULT_OK, intent);
        if (images.size() == 0){
            //toast("已保存");
            finish();
            return;
        }
        if (isFirst) {
            finish();
        }else {
            requestProductModify(images);
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        photoCore.onResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoCore.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    public void onSuccess(String path) {
        L.e("test", "path:" + path + "");
        if (currentIndex > -1 && currentIndex < imgList.size()) {
            Images images = imgList.get(currentIndex);

//            images.setFilePath(path);
            images.setType(Images.LOADING);
            adapter.clearAllStatus();
            adapter.addedView();
            RequestTag tag = new RequestTag();
            tag.action = currentIndex;
//            currentIndex = -1;
            tag.tag = "upload";
            tag.arg1 = images.getUuid();
            photoCore.uploadImage(this, images.getFilePath(), tag,uploadListener);
        }
    }

    @Override
    public void onFail(String msg) {
        toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        if (currentIndex > -1 && currentIndex < imgList.size()) {
            Images images = imgList.get(currentIndex);
            images.setType(Images.LOADING);
            adapter.notifyDataSetChanged();
            RequestTag tag = new RequestTag();
            tag.action = currentIndex;
            tag.tag = "upload";
            tag.arg1 = images.getUuid();
            photoCore.uploadImage(this, images.getFilePath(), tag,uploadListener);
        }
    }

    private void requestProductModify(List<Images> images) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_image_modify);

        RequestEntityMapSupply.putParameter("images",images);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_image_modify, onProductModifyRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductModifyRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                toast(BaseApplication.getDoc().getSaved());
                finish();
            } else {

            }

        }
    };


}
